<template>
  <!-- 门诊医生-处方 -->
  <div class="h-full">
    <div class="flex justify-between items-center p-2 mb-2 table-header">
      <a-form layout="inline" :disabled="store.radioKey || !store.currentPatient.inplsh">
        <a-form-item label="">
          <a-radio-group v-model:value="formState.inpAdvice" :options="orderTypeEnum" @change="getData" />
        </a-form-item>
        <a-form-item label="显示已作废医嘱"> <a-switch v-model:checked="showCancel" @change="getData" /> </a-form-item>
        <a-form-item label="" class="w-56 ml-4">
          <a-input-search v-model:value="formState.zjm" placeholder="项目名称/助记码" allow-clear @search="getData" />
        </a-form-item>
      </a-form>
      <a-space>
        <!-- store.radioKey  //0 在院  1 已出院 -->
        <template v-if="!isOperation">
          <a-button
            v-if="typeof applyReturnStatus == 'undefined' && !isOperation"
            type="primary"
            ghost
            :disabled="store.radioKey"
            @click="() => (applyReturnOpen = true)"
            >申请退院</a-button
          >
          <BaseButton
            v-else
            confirm-text="是否取消退院？"
            type="primary"
            danger
            ghost
            :disabled="store.radioKey || applyReturnStatus === 1 || applyReturnStatus === 2"
            @click="onCancelApplyReturn"
          >
            取消退院
          </BaseButton>
        </template>
        <a-button type="primary" danger ghost :disabled="store.radioKey || dataSource.length === 0" @click="onStopAll">全部停止</a-button>
        <a-button type="primary" ghost :disabled="store.radioKey || !store.currentPatient.inplsh" @click="onTemplate">套餐模板</a-button>
        <a-button type="primary" ghost :disabled="store.radioKey || dataSource.length === 0" @click="onPrintCheck()">打印检查单</a-button>
        <a-button type="primary" :loading="singLoading" :disabled="store.radioKey || dataSource.length === 0" @click="onSign(1)">签署</a-button>
        <!-- zyStatus 住院状态为在区 才能开立医嘱 -->
        <a-button
          ref="doctorAdviceRef"
          type="primary"
          :disabled="store.radioKey || !store.currentPatient.inplsh || store.currentPatient.zyStatus !== 0"
          @click.stop="onDoctorAdvice"
        >
          开立医嘱
        </a-button>
        <ItemModal
          v-model:open="openItemModal"
          :popover-height="popoverHeight"
          :is-operation="isOperation"
          :is-has-leave-hospital="isHasLeaveHospital"
          :row-data="rowData"
          @refresh="getData"
        />
        <!-- @save="confirmSave" -->
      </a-space>
    </div>
    <BaseTable
      :loading="loading || pageLoading"
      class="table-style"
      column-code="000103"
      :exclude-columns="isOperation ? [] : ['dj', 'je']"
      max-fill
      :extra-height="isOperation ? 60 : 0"
      :data-source="dataSource"
      :scroll="{ x: 1400 }"
      :expanded-row-keys="expandedRowKeys"
      :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
    >
      <template #bodyCell="{ column, index, record }">
        <template v-if="column.dataIndex === 'xh'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'link'">
          <div class="table-link"></div>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-tag :color="orderStatusEnum[record.status]?.color">{{ orderStatusEnum[record.status]?.name }}</a-tag>
        </template>
        <template v-if="column.dataIndex === 'advExecType'">
          <!-- 长期/临时 -->
          {{ ['临时', '长期', '出院带药'][record.advExecType] || '' }}
        </template>
        <template v-if="column.title === '处置内容'">
          <PreviewCell :row-data="record" />
        </template>
        <template v-if="column.title === '开始时间'">
          {{ record.startTime || '-' }}
        </template>
        <template v-if="column.dataIndex === 'stopTime'">
          <div v-if="record.advExecType === 0">{{ record.endTime || '-' }}</div>
          <div v-if="record.advExecType === 1">{{ record.stopTime || '-' }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <!-- 0: { name: '开立', value: 0, color: 'blue' },
          1: { name: '已签署', value: 1, color: 'success' },
          2: { name: '已签收', value: 2, color: 'success' },
          3: { name: '已申请', value: 3, color: 'success' },
          4: { name: '待执行', value: 4, color: 'success' },
          5: { name: '已执行', value: 5, color: 'success' },
          6: { name: '已停止', value: 6, color: 'red' },
          7: { name: '已作废', value: 7, color: 'red' } -->
          <a-button v-if="record?.skinTestResult >= 0" type="link" size="small" @click="onSkinTest(record)"> 皮试结果 </a-button>
          <a-button
            v-if="!record.isChild && record.status === 0 && record.boxType !== '检验'"
            type="link"
            :disabled="record.deliverRoute?.fyff === '皮试'"
            size="small"
            @click="onEdit(record)"
          >
            修改
          </a-button>
          <BaseButton v-if="record.status === 1 && !record.isChild" confirm-text="确定撤销签署?" danger type="link" size="small" @click="onSign(0, record)">
            撤销签署
          </BaseButton>
          <BaseButton
            v-if="isOperation"
            confirm-text="确定作废?"
            :disabled="!systemConfig.testStock && (record.status !== 0 || record.deliverRoute?.fyff === '皮试')"
            danger
            type="link"
            size="small"
            @click="onDelete(record, record.isChild)"
          >
            作废
          </BaseButton>
          <BaseButton
            v-else
            confirm-text="确定作废?"
            :disabled="record.status !== 0 || record.deliverRoute?.fyff === '皮试'"
            danger
            type="link"
            size="small"
            @click="onDelete(record, record.isChild)"
          >
            作废
          </BaseButton>
          <!-- 护士已签收&非子医嘱&长期 -->
          <BaseButton
            v-if="record.signNurseStatus === 1 && !record.isChild && record.advExecType === 1"
            confirm-text="确定停止?"
            danger
            type="link"
            :disabled="record.status !== 8"
            size="small"
            @click="onStop(record)"
          >
            停止
          </BaseButton>
        </template>
      </template>
      <template v-if="isOperation" #footer>
        <div class="sticky bottom-0 flex justify-end pl-20 items-center">
          <div class="text-right pr-6">
            今日手术费用 <span class="font-semibold text-base">￥{{ formatAmount(totalPrice.toDayAmount) }}</span>
          </div>
          <div class="text-right pr-6">
            手术总费用 <span class="font-semibold text-base">￥{{ formatAmount(totalPrice.amount) }}</span>
          </div>
        </div>
      </template>
    </BaseTable>
    <TemplateModal v-model:open="openTemplate" :is-operation="isOperation" :edit="true" @success="getData" />
    <SkinTestResults v-model:open="openSkinTest" :row-data="rowData" />

    <a-modal
      v-model:open="applyReturnOpen"
      width="640px"
      destroy-on-close
      title="申请退院"
      ok-text="保存"
      centered
      @ok="onApplyReturn"
      @cancel="() => (applyReturnOpen = false)"
    >
      <a-form :model="formState" class="form-style-flex">
        <a-form-item label="退院理由" class="w-full">
          <a-textarea v-model:value="cancelMemo" :rows="6" placeholder="请输入" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { getIds } from '@/utils/tools'
import ItemModal from '@/views/in-doctor/components/ItemModal'
import { getSystemConfig } from '@/utils/systemConfig'
import { formatAmount } from '@/utils/format.js'
import useStore from '../../store'
import PreviewCell from './PreviewCell'
import TemplateModal from './TemplateModal'

const props = defineProps({
  isOperation: {
    type: Boolean,
    default: false
  },
  pageLoading: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['search'])
const orderTypeEnum = [
  { value: '', label: '全部' },
  { value: 1, label: '长期' },
  { value: 0, label: '临时' }
]
const orderStatusEnum = {
  0: { name: '开立', value: 0, color: 'blue' },
  1: { name: '已签署', value: 1, color: 'success' },
  2: { name: '已签收', value: 2, color: 'success' },
  3: { name: '已申请', value: 3, color: 'success' },
  4: { name: '待执行', value: 4, color: 'success' },
  5: { name: '已执行', value: 5, color: 'success' },
  6: { name: '已停止', value: 6, color: 'red' },
  7: { name: '已作废', value: 7, color: 'red' },
  8: { name: '执行中', value: 8, color: 'blue' },
  9: { name: '已发药', value: 9, color: 'success' },
  10: { name: '退药中', value: 10, color: 'red' },
  11: { name: '已退药', value: 11, color: 'success' }
}
const store = useStore()
const loading = ref(true)
const openItemModal = ref(false)
const applyReturnOpen = ref(false)
const cancelMemo = ref('')
const openSkinTest = ref(false)
const openTemplate = ref(false)
const showCancel = ref(false)
const formState = reactive({ inpAdvice: '', zjm: '' })
// const defaultRow = () => {
//   return {
//     cydy: 0,
//     status: 0,
//     advType: 0, //医嘱类别;0:收费医嘱|1：口头医嘱
//     boxType: '全部',
//     inpAdviceType: props.isOperation ? '1' : '0', //0住院医嘱 1术后医嘱
//     inplsh: store.currentPatient.inplsh,
//     brId: store.currentPatient.brId,
//     advExecType: 1, //医嘱执行类别;0：临时 1：长期 2：出院带药
//     fid: ''
//   }
// }
const expandedRowKeys = ref(['row-0'])
const popoverHeight = ref(0)
const dataSource = ref([])
const totalPrice = ref({})
const doctorAdviceRef = ref(null)
const getHeigth = () => {
  const rect = doctorAdviceRef.value?.$el?.getBoundingClientRect()
  popoverHeight.value = window.innerHeight - rect.top - rect.height - 28
}
const rowData = ref({})
const onDoctorAdvice = () => {
  rowData.value = {}
  openItemModal.value = true
}
const onEdit = (row) => {
  rowData.value = JSON.parse(JSON.stringify(row))
  if (rowData.value.children?.length > 0) {
    rowData.value.children = rowData.value.children.filter((r) => r.status !== 7)
  }
  openItemModal.value = true
}

//计算总价
const onCalcTotal = async () => {
  const { code, data } = await post('/inp/clinicalOrder/getSsfy', { inplsh: store.currentPatient.inplsh })
  if (code !== 0) return
  totalPrice.value = data || '0.00'
}
// //保存
// const onSave = async () => {
//   const { code, msg } = await post('/inp/clinicalOrder/doSavePatientClinicalOrderList', dataSource.value)
//   if (code !== 0) return message.error(msg || '保存失败')
//   message.success('保存成功')
//   getData()
// }

//停止医嘱
const onStop = async (row) => {
  const { code, msg } = await post('/inp/clinicalOrder/doStopClinicalOrder', {
    inpAdvId: row.id
  })
  if (code !== 0) return message.error(msg || '停止失败')
  message.success('停止成功')
  getData()
}
//申请退院
const onApplyReturn = async () => {
  const { code, msg } = await post('/inp/zyys/doApplyInpRevocation', {
    inplsh: store.currentPatient.inplsh,
    cancelMemo: cancelMemo.value,
    status: 0
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('操作成功')
  applyReturnOpen.value = false
  getApplyReturnStatus()
}
//取消申请退院
const onCancelApplyReturn = async () => {
  const { code, msg } = await post('/inp/zyys/doApplyInpRevocation', {
    inplsh: store.currentPatient.inplsh,
    cancelMemo: '',
    status: null
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('操作成功')
  getApplyReturnStatus()
}
const applyReturnStatus = ref()
//获取状态
const getApplyReturnStatus = async () => {
  const { code, msg, data } = await post('/inp/zyys/doGetStatusInpRevocation', {
    inplsh: store.currentPatient.inplsh
  })
  if (code !== 0) return message.error(msg)
  applyReturnStatus.value = data
}
//停止全部医嘱
const onStopAll = async () => {
  const list = dataSource.value.filter((item) => item.advExecType === 1)
  const ids = getIds(list)
  const { code, msg } = await post('/inp/clinicalOrder/doStopClinicalOrderAll', {
    inpAdvId: ids
  })
  if (code !== 0) return message.error(msg || '停止失败')
  message.success('停止成功')
  getData()
}
//作废医嘱
const onDelete = async (row, isChild) => {
  if (row.isNew) {
    if (isChild) {
      const fData = dataSource.value.find((item) => item.key === row.fkey)
      const index = fData.children.findIndex((item) => item.key === row.key)
      fData.children.splice(index, 1)
    } else {
      const index = dataSource.value.findIndex((item) => item.key === row.key)
      dataSource.value.splice(index, 1)
    }
  } else {
    const { code, msg } = await post('/inp/clinicalOrder/doCancelClinicalOrder', { inpAdvId: row.id, szyzOperate: props.isOperation })
    if (code !== 0) return message.error(msg || '作废失败')
    message.success('作废成功')
    emit('search')
    getData()
  }
}
const singLoading = ref(false)
//签署
const onSign = async (signStatus, row) => {
  // const list = dataSource.value.filter((item) => item.beUpdate !== '1')
  const ids = getIds(dataSource.value)
  const { code, msg } = await post(
    '/inp/clinicalOrder/signedDoctor',
    { inpAdvIds: row?.id ? [row.id] : ids, signStatus, szyzOperate: props.isOperation },
    {
      singLoading: true
    }
  )
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('操作成功')
  emit('search')
  getData()
}
const isHasLeaveHospital = ref(false)
//获取数据
const getData = async () => {
  if (!store.currentPatient.inplsh) {
    dataSource.value = []
    loading.value = false
    return
  }
  totalPrice.value = {}
  loading.value = true
  const res = await post('/inp/zyys/getClinicalOrderInfoList', {
    isDisplayed: showCancel.value ? '1' : '0',
    inpAdvice: formState.inpAdvice, //医嘱执行类别
    zjm: formState.zjm,
    inpAdviceType: props.isOperation ? '1' : '0', //0住院医嘱 1术后医嘱
    inplsh: store.currentPatient.inplsh,
    aptmLsh: props.isOperation ? store.currentPatient.aptmLsh : undefined
  })
  loading.value = false
  if (res.code !== 0) return message.error(res.msg || '获取数据失败')
  if (res.data.length) {
    dataSource.value = res.data.map((item) => {
      item.key = item.id
      if (item.boxType === '出院') {
        isHasLeaveHospital.value = true
      }
      if (item.children?.length) {
        expandedRowKeys.value.push(item.id)
        item.children = item.children.map((child) => ({ ...child, key: child.id, isChild: true }))
      }
      return item
    })
    openItemModal.value && onSaveTest()
    if (props.isOperation) onCalcTotal()
  } else {
    dataSource.value = []
    // dataSource.value = [{ key: 'row-0', children: [], ...defaultRow() }]
  }
}

// 检验
const onSaveTest = async () => {
  const result = dataSource.value.filter((item) => item.status === 0 && item.id).map((item) => item.id) // 过滤出未签署的并且 从每个对象中提取 id
  const { code, msg } = await post('/inp/zyys/signedInpDoSaveLisApply', { inpAdvIds: result })
  if (code !== 0) return message.error(msg || '操作失败')
}

// 检验
const onPrintCheck = async () => {
  const { code, data, msg } = await post('/inp/Print/printYSJCD', { inplsh: store.currentPatient.inplsh })
  if (code !== 0) return message.error(msg || '打印失败')
  window.openExe?.rpt(data) //调用winform打印
}

// const confirmSave = async (params) => {
//   if (params.boxType !== '西成药') return
//   const { code, data, msg } = await post('/common/masterData/getSkinTestDrugInfo', {
//     bh: params?.adv?.bh,
//     jzbh: store.currentPatient.jzbh
//   })
//   if (code !== 0) return message.error(msg)
//   if (!data?.bh) return
// }
//更新行数据
// const onUpdateRow = (row, newData) => {
//   for (const key in newData) {
//     if (Object.hasOwnProperty.call(newData, key)) {
//       row[key] = newData[key]
//     }
//   }
// }

const onSkinTest = (row) => {
  rowData.value = { ...row, mc: row.advName }
  openSkinTest.value = true
}
const onTemplate = () => {
  openTemplate.value = true
}
watch(
  () => store.currentPatient?.inplsh,
  (val) => {
    if (val) {
      getData()
      getApplyReturnStatus()
      rowData.value = {}
      openItemModal.value = false
    } else {
      loading.value = false
      rowData.value = {}
      openItemModal.value = false
    }
  },
  { immediate: true }
)
const systemConfig = ref({})
onMounted(() => {
  systemConfig.value.testStock = getSystemConfig('OPR_ADVICE_SELF_DEPT_DEDUCTING_INVETORY') === '1' //关闭为0 打开为1 | 0：走物资发放模块|1：直接扣减本科室库存
  getHeigth()
})
</script>
<style lang="less" scoped>
.table-header {
  background: var(--thin-color);
  &:first-child {
    margin-top: 0;
  }
}

:deep(.ant-table-row-expand-icon) {
  display: none;
}
:deep(.ant-table-row-indent) {
  display: none;
}
</style>
